// Copyright (c) 2021 RonxBulld
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <iostream>
#include <yamq.h>

class ConsoleOut {
private:
    std::string prompt_;
public:
    explicit ConsoleOut(const std::string &prompt = "") : prompt_(prompt) {}
    void WriteOut(const std::string &str) {
        std::cout << prompt_ << ": " << str << std::endl;
    }
};

template <class T>
class Observer : public yamq::ObserverBase {
private:
    ConsoleOut &console_out_;

public:
    explicit Observer(ConsoleOut &CO) : console_out_(CO) {}

    void Invoke(const yamq::KVdb &kvdb) override {
        console_out_.WriteOut(kvdb[""] + kvdb["i"]);
    }

    ~Observer() override = default ;
};

int main() {
    ConsoleOut co("Test");
    ConsoleOut ck("Echo");

    Observer<std::string> obi(co);
    Observer<long> *obk = new Observer<long>(ck);

    yamq::PubSub<yamq::SerialSlot> pubsub;
    pubsub.Subscribe("aaa", obi);
    pubsub.Subscribe("aaa", *obk);
    pubsub.Subscribe("bbb", [](const yamq::KVdb &kvdb){
        std::cout << "Lambda recived: " << kvdb[""] << std::endl;
    });
    bool obi_reg = true;

    yamq::KVdb kvdb;
    kvdb[""] = "Resolved.";

    int i = 0;
    while(i++ < 10000) {
        kvdb["i"] = std::to_string(i);
        pubsub.Publish("aaa", kvdb);
        if ((i >= 5000) && obk) {
            obk->DisableAndWait();
            delete obk;
            obk = nullptr;
        }
        if (obi_reg && (i >= 1000)) {
            obi.Disconnect(&pubsub);
            obi_reg = false;
        }
    }

    return 0;
}
